import store from "@/vuex/store";

function arrayToTree(array = []) {
  let array_ = []; // 创建储存剔除叶子节点后的骨架节点数组
  let unique = {}; // 创建盒子辅助本轮children合并去重
  let root_pid = [
    0,
    "0",
    undefined,
    "undefined",
    "",
    null,
    "null"
  ]; // 可能存在的根节点pid形式
  for (let index = 0; index < array.length; index++) {
    const item = array[index];
    // 筛选可以插入当前节点的所有子节点
    let children_array = array.filter(
      it => String(it.pid) === String(item.id)
    );
    //console.log(children_array)
    //item.children instanceof Array 检测item.children是否是数组
    if (item.children && item.children instanceof Array && item.children.length > 0) {
      // 去重合并数组
      item.children.map(i => (unique[i.id] = 1));
      // console.log(unique)
      item.children.push(
        ...children_array.filter(i => unique[i.id] !== 1)
      );
    } else {
      item.children = children_array;
    }
    // 当children_array有数据时插入下一轮array_，当无数据时将最后留下来的根节点树形插入数组
    let has_children = children_array.length > 0;
    if (
      has_children ||
      (!has_children && root_pid.includes(item.pid))
    ) {
      array_.push(item);
    }
  }
  // 当数组内仅有根节点时退出，否组继续处理 最终递归深度次
  if (!array_.every(item => root_pid.includes(item.pid))) {
    //console.log(array_)
    return arrayToTree(array_);
  } else {
    return array_;
  }
}

//下载文件
function downLoad(content, fileName) {
  var aEle = document.createElement("a"); // 创建a标签
  aEle.href = content;
  aEle.target = "_blank"
  aEle.click(); // 设置点击事件
}


//后台获取列表数据
function getDJData(params, api) {

  let allparams = {
    params: params,
    api: api,
  }
  store
    .dispatch("getmsgData", allparams)
    .then(response => {
      // this.loading = false;
      let res = response.data;
      return {
        type: true,
        res: res
      }
    })
    .catch(err => {
      console.log(err);
      return {
        type: false
      }
    });
}


export {
  arrayToTree, // 将数组转化成树结构
  downLoad,
  getDJData
}
